package main.controller;

import main.*;
import main.database.AccountHelper;
import main.database.AuthorHelper;
import main.database.NotifyHelper;
import main.database.StatisticHelper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@Controller
public class AuthorPageController {
    @RequestMapping (value = "/author/{id}")
    public String authorPage(HttpServletRequest request, ModelMap modelMap, @PathVariable(value="id") String id) {
        String targetUrl = "redirect:/articlenotfound";
        String uuid = RequestHelper.getUserUUIDFromRequest(request);
        String account = AccountHelper.getAccountInfoFromUUID(uuid);
        boolean isLogin = true;
        if (account == null || account.isEmpty()) {
            isLogin = false;
        }

        String user = "";
        if (isLogin) {
            user = uuid;
        }
        StatisticHelper.addAuthorPageAccess(uuid, NetworkHelper.getIPAddress(request), TimeHelper.getFormattedNowString(), UserAgentHelper.getUserAgent(request));

        if (!id.isEmpty()) {
            Map<String, String> infos = AuthorHelper.getInfomationFromId(id);
            if (infos != null) {
                List<String[]> articleList = AuthorHelper.getAuthorArticleList(id);

                long unread = NotifyHelper.countUnreadNotify(uuid);
                String baseUrl = UriHelper.getServerBaseUri(request);

                boolean isAdmin = AccountHelper.isAdminFromUUID(uuid);

                modelMap.put("siteName", GlobalConfig.siteName);
                modelMap.put("serverUri", baseUrl);
                modelMap.put("title", infos.get("name"));
                modelMap.put("introduction", infos.get("introduction"));
                modelMap.put("isLogin", isLogin);
                modelMap.put("isAdmin", isAdmin);
                modelMap.put("artileList", articleList);
                modelMap.put("unread", unread);
                modelMap.put("year2year", TimeHelper.getFormattedYear2Year());

                targetUrl = "authorPage";
            }
        }
        return targetUrl;
    }
}
